﻿using B.S.Production.Domain.Entities;
using B.S.Production.ErrorCode;
using B.S.Production.Read.API.Application.Command.GetProductionOrderCommand;
using MediatR;
using SqlSugar;

namespace B.S.Production.Read.API.Application.CommandHandler.GetProductionOrderCommandHandler
{
    public class GetProductionOrderCommandHandler : IRequestHandler<GetProductionOrderCommand, ApiResult<List<ProductionOrder>>>
    {
        private readonly ISqlSugarClient db;

        public GetProductionOrderCommandHandler(ISqlSugarClient db)
        {
            this.db = db;
        }

        public async Task<ApiResult<List<ProductionOrder>>> Handle(GetProductionOrderCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<ProductionOrder>> result = new ApiResult<List<ProductionOrder>>();
            try
            {
                var list = await db.Queryable<ProductionOrder>().ToListAsync();
                result.Data = list;

                if (result.Data != null && result.Data.Count > 0)
                {
                    result.Code = ApiEnums.查询成功;
                    result.Msg = ApiEnums.查询成功.ToString();
                }
                else
                {
                    result.Code = ApiEnums.查询失败;
                    result.Msg = ApiEnums.查询失败.ToString();
                }
            }
            catch (Exception ex)
            {
                result.Code = ApiEnums.查询失败;
                result.Msg = $"查询失败: {ex.Message}";
            }

            return result;
        }
    }
}
